from jinja2 import Template
import os
import yaml

def read_yaml(file):
    stream = open(file, "r")
    docs = yaml.load(stream)
    return docs

def render_str(patten, data):
    patten = patten.decode('utf-8')
    s = Template(patten)
    ret = s.render(data)
    return ret

def render_file(template_file, data, target_file):
    if not os.path.isfile(template_file):
        return
    ensure_dir_for_file(target_file)
    with open(template_file, 'r') as f:
        patten = f.read()
        result = render_str(patten, data)
        with open(target_file, 'w') as fw:
            fw.write(result.encode('utf-8'))

def ensure_dir(dir):
    if not os.path.exists(dir):
        os.makedirs(dir)

def ensure_dir_for_file(file):
    ensure_dir(os.path.dirname(file))

def underscore_to_camelcase(value):
    def camelcase():
        yield str.lower
        while True:
            yield str.capitalize

    c = camelcase()
    return "".join(next(c)(x) if x else '_' for x in value.split("_"))
